#include "Subsystems/BlockBehaviors/SubsystemCraftingTableBlockBehavior.h"
#include "Subsystems/SubsystemBlockEntities.h"

#include "Managers/EntityManager.h"
#include "Components/ComponentBlockEntity.h"
#include "Components/ComponentCraftingTable.h"

#include "Blocks/CraftingTableBlock.h"
#include "GameSingleton.h"
#include "GameRegistry.hpp"
#include "Log.h"


namespace PocketSurvival
{
    SubsystemCraftingTableBlockBehavior::SubsystemCraftingTableBlockBehavior()
    {
        m_handleBlocks.push_back(CraftingTableBlock::Index());
    }

    void SubsystemCraftingTableBlockBehavior::onBlockAdded(int32_t value, int32_t oldValue, int32_t x, int32_t y, int32_t z)
    {
        Point3 point(x,y,z);
        m_subsystemBlockEntities->addBlockEntity("CraftingTable", point);
    }

	void SubsystemCraftingTableBlockBehavior::onBlockRemoved(int32_t value, int32_t newValue, int32_t x, int32_t y, int32_t z)
    {
        std::lock_guard<std::recursive_mutex> lk(m_subsystemBlockEntities->blockEntitiesMutex);

        ComponentBlockEntity *blockEntity = m_subsystemBlockEntities->findBlockEntity(x, y, z);
        if(blockEntity != nullptr)
        {
            Vector3 position(x, y, z);
            position += 0.5f;
            ComponentCraftingTable *componentCraftingTable = GameSingleton::gameRegistry->get<ComponentCraftingTable*>(blockEntity->entity);
            componentCraftingTable->dropAllItems(position);
            m_subsystemBlockEntities->removeBlockEntity(blockEntity);
        }
    }

    bool SubsystemCraftingTableBlockBehavior::onInteract(const TerrainRaycastResult &raycastResult, ComponentMiner *componentMiner)
    {
        return false;
    }

    static const std::string subsystemName = "CraftingTableBlockBehavior";
    const std::string& SubsystemCraftingTableBlockBehavior::getName() const
    {
        return subsystemName;
    }
    void SubsystemCraftingTableBlockBehavior::load(const nlohmann::json &json)
    {
        m_subsystemBlockEntities = GameSingleton::singletonPtr->getSingleton<SubsystemBlockEntities>();
    }
}